package com.wonders.module.utils;


import com.wonders.module.mail.model.MailSendInfo;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.util.Date;
import java.util.Properties;

public class SendMail {
	

	public boolean sendTextMail(MailSendInfo mailInfo, String nicheng, String title, String text){
		
		Properties pro = new Properties();
		//创建信件服务器
		pro.put("mail.smtp.host",mailInfo.getMailServerHost());
		pro.put("mail.smtp.port",mailInfo.getMailServerPort());  
		pro.put("mail.smtp.auth",mailInfo.isValidate()?"true":"false");  
		
		MyAuthenticator myAuthenticator = null;
		if(mailInfo.isValidate()){
			myAuthenticator = new MyAuthenticator(mailInfo.getUsername(),mailInfo.getPassword());
		}
		//创建session实例
		Session sendMailSession = Session.getDefaultInstance(pro,myAuthenticator);
		try{
			
			Message mailMessage = new MimeMessage(sendMailSession);
			//设置自定义发件人昵称
			String nick = MimeUtility.encodeText(nicheng);
			Address from = new InternetAddress(nick+"<"+mailInfo.getFromaddress()+">");
			
			mailMessage.setFrom(from);   
			Address to = new InternetAddress(mailInfo.getToaddress());
			mailMessage.setRecipient(Message.RecipientType.TO, to);
			mailMessage.setSubject(title);
			mailMessage.setSentDate(new Date());
			mailMessage.setText(text);
			Transport.send(mailMessage);
			return true;
		}catch (Exception e) {  
			e.printStackTrace();
		}
		return false;
	}
	
}
